package com.open4cn.simulator.core.parser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

/**
 * @author yinxiaopeng
 * @version 1.0.0
 * @company 致景科技
 * @department 飞梭BU/研发
 * @description
 * @Email yinxiaopeng@zj.tech
 * @date 2022-04-05 23:21
 */
public class InstructionParserChain {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 全部指令分析器
    private List<IInstructionParser> allParser;

    // 后续链
    private InstructionParserChain nextChain;

    // 当前指令分析器
    private IInstructionParser currentParser;

    public InstructionParserChain(List<IInstructionParser> parsers) {
        this.allParser = Collections.unmodifiableList(parsers);
        InstructionParserChain chain = initChain(parsers);
        this.currentParser = chain.currentParser;
        this.nextChain = chain.nextChain;
    }

    private InstructionParserChain(List<IInstructionParser> parsers, IInstructionParser currentParser, InstructionParserChain chain) {
        this.allParser = parsers;
        this.currentParser = currentParser;
        this.nextChain = chain;
    }

    /**
     * 组装指令分析链
     *
     * @param parsers
     * @return
     */
    private InstructionParserChain initChain(List<IInstructionParser> parsers) {
        InstructionParserChain chain = new InstructionParserChain(parsers, null, null);
        ListIterator<? extends IInstructionParser> iterator = parsers.listIterator(parsers.size());
        while (iterator.hasPrevious()) {
            chain = new InstructionParserChain(parsers, iterator.previous(), chain);
        }
        return chain;
    }


    public Object filter(Object msg) {
        if (this.currentParser != null) {
            try {
                return currentParser.parse(msg, this.nextChain);
            } catch (Exception e) {
                logger.warn("指令解析异常", e);
            }
        }
        return null;
    }
}
